
package com.ruoyi.busi.guide.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import org.springframework.util.CollectionUtils;
import com.mybatisflex.core.service.IService;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ruoyi.busi.guide.domain.*;
import com.ruoyi.busi.guide.domain.dto.MentorDetailDTO;
import com.ruoyi.busi.guide.domain.dto.MentorRequestDTO;
import com.ruoyi.busi.guide.mapper.*;
import com.ruoyi.busi.guide.service.IMentorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

/**
 * 导师信息Service业务层处理
 */
@Service
public class MentorServiceImpl extends ServiceImpl<MentorMapper, Mentor> implements IMentorService {
    private static final Logger log = LoggerFactory.getLogger(MentorServiceImpl.class);

    @Autowired
    private EducationMapper educationMapper;
    
    @Autowired
    private ExperienceMapper experienceMapper;
    
    @Autowired
    private AbilityMapper abilityMapper;

    /**
     * 查询导师列表
     */
    @Autowired
    private MentorMapper mentorMapper;
    
    @Override
    public List<Mentor> selectMentorList(Mentor mentor) {
        return mentorMapper.selectMentorList(mentor);
    }

    /**
     * 新增导师(兼容旧接口，仅处理教育经历)
     */
    @Override
    @Transactional
    public boolean save(Mentor mentor) {
        // 保存导师基本信息
        boolean saved = super.save(mentor);
        return saved;
    }

    /**
     * 新增导师及其关联的教育经历、工作经历和能力评估
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveWithExperiences(Mentor mentor, List<Education> educations, List<Experience> experiences, MentorRequestDTO mentorDTO) {
        try {
            log.info("开始保存导师信息: {}", mentor);
            // 保存导师基本信息
            log.debug("保存前mentorId值: {}", mentor.getMentorId());
            boolean saved = super.save(mentor);
            if (!saved) {
                log.error("保存导师基本信息失败");
                return false;
            }
            
            Long mentorId = mentor.getMentorId();
            log.debug("保存后mentorId值: {}", mentorId);
            if (mentorId == null || mentorId <= 0) {
                log.error("导师ID生成异常: mentorId={}", mentorId);
                throw new RuntimeException("导师ID生成异常");
            }
            log.info("导师基本信息保存成功, mentorId={}", mentorId);
            log.debug("完整的导师对象: {}", mentor);
            
            // 保存教育经历
            if (educations != null && !educations.isEmpty()) {
                log.info("开始保存{}条教育经历", educations.size());
                for (Education education : educations) {
                    education.setMentorId(mentorId);
                    log.info("设置教育经历的mentorId: {}", mentorId);
                    log.debug("准备插入教育经历: {}", education);
                    int result = educationMapper.insert(education);
                    if (result <= 0) {
                        log.error("插入教育经历失败 - mentorId: {}, education: {}", mentorId, education);
                        throw new RuntimeException("插入教育经历失败");
                    }
                    log.debug("教育经历插入成功, 影响行数: {}", result);
                }
                log.info("教育经历保存成功");
            } else {
                log.info("无教育经历需要保存");
            }
            
            // 保存工作经历
            if (experiences != null && !experiences.isEmpty()) {
                log.info("开始保存{}条工作经历", experiences.size());
                for (Experience experience : experiences) {
                    experience.setMentorId(mentorId);
                    log.info("设置工作经历的mentorId: {}", mentorId);
                    log.debug("准备插入工作经历: {}", experience);
                    int result = experienceMapper.insert(experience);
                    if (result <= 0) {
                        log.error("插入工作经历失败 - mentorId: {}, experience: {}", mentorId, experience);
                        throw new RuntimeException("插入工作经历失败");
                    }
                    log.debug("工作经历插入成功, 影响行数: {}", result);
                }
                log.info("工作经历保存成功");
            } else {
                log.info("无工作经历需要保存");
            }
            
            // 保存能力评估
            if (mentorDTO.getAbilities() != null) {
                Ability ability = mentorDTO.getAbilities();
                ability.setMentorId(mentorId);
                log.info("准备保存能力评估 - mentorId: {}", mentorId);
                log.debug("能力评估详情 - 技术能力: {}, 管理能力: {}, 沟通能力: {}, 创新能力: {}, 教学能力: {}, 研究能力: {}, 指导能力: {}",
                    ability.getTechnicalAbility(), ability.getManagementAbility(), 
                    ability.getCommunicationAbility(), ability.getInnovationAbility(),
                    ability.getTeachingAbility(), ability.getResearchAbility(), 
                    ability.getMentoringAbility());
                
                int result = abilityMapper.insert(ability);
                if (result <= 0) {
                    log.error("插入能力评估失败 - mentorId: {}, ability: {}", mentorId, ability);
                    throw new RuntimeException("插入能力评估失败");
                }
                log.debug("能力评估插入成功, 影响行数: {}", result);
                log.info("能力评估保存成功");
            } else {
                log.info("无能力评估需要保存");
            }
            
            return true;
        } catch (Exception e) {
            log.error("保存导师信息过程中发生异常", e);
            throw e;
        }
    }

    /**
     * 批量删除导师
     */
    @Autowired
    private TaskMapper taskMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMentorByIds(List<Long> mentorIds) {
        if (CollectionUtils.isEmpty(mentorIds)) {
            return false;
        }
        
        // 检查每个导师是否有未完成任务
        for (Long mentorId : mentorIds) {
            int unfinishedTaskCount = taskMapper.countByMentorIdAndStatusNotIn(
                mentorId, List.of("已完成", "已取消"));
            if (unfinishedTaskCount > 0) {
                throw new RuntimeException("导师ID " + mentorId + " 有未完成的任务，不能删除");
            }
        }
        
        // 先删除关联的教育经历
        educationMapper.deleteByMentorIds(mentorIds);
        // 删除关联的工作经历
        experienceMapper.deleteByMentorIds(mentorIds);
        // 删除关联的能力评估
        abilityMapper.deleteByMentorIds(mentorIds);
        
        // 再删除导师信息
        return this.removeByIds(mentorIds);
    }

    @Override
    public MentorDetailDTO getMentorDetail(Long mentorId) {
        MentorDetailDTO dto = new MentorDetailDTO();
        // 查询导师基本信息
        Mentor mentor = this.getById(mentorId);
        log.info("查询到导师基本信息: {}", mentor);
        dto.setMentor(mentor);
        
        // 查询教育经历
        List<Education> educations = educationMapper.selectByMentorId(mentorId);
        log.info("查询到教育经历数据: {}", educations);
        dto.setEducations(educations);
        
        // 查询工作经历
        List<Experience> experiences = experienceMapper.selectByMentorId(mentorId);
        log.info("查询到工作经历数据: {}", experiences);
        dto.setExperiences(experiences);
        
        // 查询能力
        Ability ability = abilityMapper.selectByMentorId(mentorId);
        log.info("查询到能力数据: {}", ability);
        dto.setAbility(ability);
        
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateWithExperiences(Mentor mentor, List<Education> educations, List<Experience> experiences, MentorRequestDTO mentorDTO) {
        try {
            log.info("开始更新导师信息: {}", mentor);
            // 更新导师基本信息
            boolean updated = super.updateById(mentor);
            if (!updated) {
                log.error("更新导师基本信息失败");
                return false;
            }
            
            Long mentorId = mentor.getMentorId();
            log.info("导师基本信息更新成功, mentorId={}", mentorId);
            
            // 更新教育经历 - 先删除旧的再插入新的
            if (educations != null) {
                log.info("开始更新教育经历，共{}条", educations.size());
                educationMapper.deleteByMentorIds(List.of(mentorId));
                if (!educations.isEmpty()) {
                    for (Education education : educations) {
                        education.setMentorId(mentorId);
                        int result = educationMapper.insert(education);
                        if (result <= 0) {
                            log.error("插入教育经历失败 - mentorId: {}, education: {}", mentorId, education);
                            throw new RuntimeException("插入教育经历失败");
                        }
                    }
                }
                log.info("教育经历更新完成");
            }
            
            // 更新工作经历 - 先删除旧的再插入新的
            if (experiences != null) {
                log.info("开始更新工作经历，共{}条", experiences.size());
                experienceMapper.deleteByMentorIds(List.of(mentorId));
                if (!experiences.isEmpty()) {
                    for (Experience experience : experiences) {
                        experience.setMentorId(mentorId);
                        int result = experienceMapper.insert(experience);
                        if (result <= 0) {
                            log.error("插入工作经历失败 - mentorId: {}, experience: {}", mentorId, experience);
                            throw new RuntimeException("插入工作经历失败");
                        }
                    }
                }
                log.info("工作经历更新完成");
            }
            
            // 更新能力评估
            if (mentorDTO.getAbilities() != null) {
                log.info("开始更新能力评估");
                abilityMapper.deleteByMentorIds(List.of(mentorId));
                Ability ability = mentorDTO.getAbilities();
                ability.setMentorId(mentorId);
                int result = abilityMapper.insert(ability);
                if (result <= 0) {
                    log.error("插入能力评估失败 - mentorId: {}, ability: {}", mentorId, ability);
                    throw new RuntimeException("插入能力评估失败");
                }
                log.info("能力评估更新完成");
            }
            
            return true;
        } catch (Exception e) {
            log.error("更新导师信息过程中发生异常", e);
            throw e;
        }
    }
}
